package br.unifor.mia.graph.setorcensitario;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Transaction;
import org.jgrapht.graph.SimpleGraph;

import br.unifor.mia.graph.util.DB;

public class SectorGraphFactory {
	
	public static void populateDB(List<Node> userNodeList) {
		
		Transaction trans = DB.getSession().beginTransaction();
		
		SimpleGraph<String, SectorLink> sectorGraph = new SimpleGraph<String, SectorLink>(SectorLink.class);

		for (Node user : userNodeList) {

			Set<Link> tailLinks = user.getUserLinks();
			Set<Link> headLinks = user.getUserLinks();

			for (Link tail : tailLinks) {
				for (Link head : headLinks) {
					if (!head.equals(tail) && !sectorGraph.containsEdge(tail.getSector().getName(), head.getSector().getName())) {
						String linkName = "from"+ tail.getSector().getName() + "_to"+ head.getSector().getName();
						
						SectorLink link = new SectorLink(linkName, tail.getSector(), head.getSector());
						DB.getSession().save(link);
						
						sectorGraph.addVertex(tail.getSector().getName());
						sectorGraph.addVertex(head.getSector().getName());
						sectorGraph.addEdge(tail.getSector().getName(), head.getSector().getName(), link);
					}
				}
			}
		}
		
		trans.commit();
	}
	
	public static void create() throws IOException {

		Query query = DB.getSession().createQuery("select sl from SectorLink sl where sl.name = :name");

		BufferedReader reader = new SectorLinkNameArray().getReader();
		
		String sectorLinkName = null;
		
		do {
			sectorLinkName = reader.readLine();
	
			query.setString("name", sectorLinkName);
			SectorLink sectorLink = (SectorLink) query.uniqueResult();
			
			Transaction trans = DB.getSession().beginTransaction();
			
			sectorLink.inicializeInfoUserSet();
			
			trans.commit();

		} while (sectorLinkName != null);
	}
}
